const Base = require('./base.js');

module.exports = class extends Base {
  async indexAction() {
    const uid = this.ctx.state.uid;
    const user = await think.model('users').where({uid: uid}).find();
    this.assign('user', user);

    // 文章统计信息
    const myPublishedCommentsNumber = await think.model('comments').getPublishedCommentsNumberByCid(uid);
    const myPublishedPostsNumber = await think.model('contents').getPublishedPostsNumberByUid(uid);
    const categoriesNumber = await think.model('metas').getCategoriesNumber();
    this.assign('myPublishedCommentsNumber', myPublishedCommentsNumber);
    this.assign('myPublishedPostsNumber', myPublishedPostsNumber);
    this.assign('categoriesNumber', categoriesNumber);

    return this.display();
  }

  async updateProfileAction() {
    const mail = this.post('mail');
    let screenName = this.post('screenName');
    const url = this.post('url');
    if (think.isEmpty(screenName)) {
      screenName = this.ctx.state.user.name;
    }

    await think.model('users').where({uid: this.ctx.state.uid}).update({
      mail: mail,
      url: url,
      screenName: screenName
    });

    return this.redirect('/admin/profile/index');
  }

  async updatePasswordAction() {
    const password = this.post('password');
    const confirm = this.post('confirm');

    if (think.isEmpty(password) || think.isEmpty(confirm)) {
      return this.redirect('/admin/profile/index');
    }

    const userService = think.service('user', 'common');
    const salt = userService.generateSalt();
    const md5Password = userService.generateMd5Password(password, salt);
    await think.model('users').where({uid: this.ctx.state.uid}).update({
      password: md5Password,
      salt: salt
    });

    return this.redirect('/admin/profile/index');
  }
};
